from flask import Flask, request, jsonify, render_template_string
import math

app = Flask(__name__)

# 5606航空液压油物理属性
class HydraulicOil5606:
    def __init__(self):
        self.density_20C = 0.85  # g/cm³ at 20°C
        self.thermal_expansion = 0.0007  # 1/°C 热膨胀系数
        self.compressibility = 0.00005  # 1/bar 压缩系数
        self.reference_temp = 20  # °C
        self.reference_pressure = 1.013  # bar
        
    def calculate_volume_change(self, initial_volume, temp, pressure):
        """计算温度-压力耦合作用下的体积变化"""
        delta_temp = temp - self.reference_temp
        delta_pressure = pressure - self.reference_pressure
        
        # 热膨胀引起的体积变化
        thermal_expansion = initial_volume * self.thermal_expansion * delta_temp
        
        # 压力压缩引起的体积变化
        pressure_compression = -initial_volume * self.compressibility * delta_pressure
        
        # 总变化量（考虑温度影响大于压力影响）
        total_change = thermal_expansion + pressure_compression * 0.3
        
        return total_change

# 液压系统计算器
class HydraulicSystemCalculator:
    def __init__(self):
        self.oil = HydraulicOil5606()
        self.initial_volume = 50  # 初始油箱容积 升
        
    def calculate_tank_level(self, components, temperature, pressure):
        """计算油箱液位"""
        # 基础体积变化
        base_change = self.oil.calculate_volume_change(
            self.initial_volume, temperature, pressure
        )
        
        # 计算各元件对油液容积的影响
        accumulator_volume = 0
        cylinder_displacement = 0
        
        for component in components:
            if component['type'] == 'accumulator':
                # 蓄能器气体体积变化
                accumulator_volume += self._calculate_accumulator_volume(
                    component, pressure
                )
            elif component['type'] == 'cylinder':
                # 油缸排量
                cylinder_displacement += self._calculate_cylinder_displacement(
                    component
                )
        
        # 总液位变化
        total_change = base_change + accumulator_volume + cylinder_displacement
        
        # 当前液位
        current_level = self.initial_volume + total_change
        
        return {
            'current_level': round(current_level, 2),
            'level_change': round(total_change, 2),
            'base_change': round(base_change, 2),
            'accumulator_effect': round(accumulator_volume, 2),
            'cylinder_effect': round(cylinder_displacement, 2)
        }
    
    def _calculate_accumulator_volume(self, accumulator, pressure):
        """计算蓄能器对油液容积的影响"""
        # 简化的蓄能器计算
        precharge = accumulator.get('precharge', 70)  # bar
        volume = accumulator.get('volume', 1)  # 升
        
        # 气体状态方程 PV = 常数
        if pressure > precharge:
            gas_volume = precharge * volume / pressure
            return volume - gas_volume
        return 0
    
    def _calculate_cylinder_displacement(self, cylinder):
        """计算油缸排量"""
        bore = cylinder.get('bore', 50)  # mm
        rod = cylinder.get('rod', 25)  # mm
        stroke = cylinder.get('stroke', 200)  # mm
        
        # 计算活塞面积
        piston_area = math.pi * (bore/2)**2 / 100  # cm²
        rod_area = math.pi * (rod/2)**2 / 100  # cm²
        
        # 对称/非对称油缸排量
        if cylinder.get('symmetric', True):
            displacement = piston_area * stroke / 1000  # 升
        else:
            displacement = (piston_area - rod_area) * stroke / 1000  # 升
            
        return displacement

calculator = HydraulicSystemCalculator()

@app.route('/')
def index():
    return render_template_string(open('index.html').read())

@app.route('/calculate', methods=['POST'])
def calculate():
    try:
        data = request.json
        temperature = float(data.get('temperature', 20))
        pressure = float(data.get('pressure', 1.013))
        components = data.get('components', [])
        
        result = calculator.calculate_tank_level(
            components, temperature, pressure
        )
        
        return jsonify({
            'success': True,
            'data': result
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        })

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
